package gui.menuItems;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;

import javax.swing.JMenuItem;

import network.GUICoreProxy;
import network.GlobalObjectId;
import network.HyPeerWebSegmentProxy;
import network.LocalObjectId;
import network.ObjectDB;
import network.PortNumber;
import gui.Main.GUI;
import gui.Main.GUICore;
import hypeerweb.HyPeerWebSegmentCreator;

/**
 * Represents the start session menu item presented in the Help menu
 * 
 * @author Matthew Smith
 */
public class StartSessionMenuItem extends JMenuItem implements ActionListener {

	GUI main;

	/**
	 * Creates a Start Session menu Item
	 * 
	 * @param main
	 */
	public StartSessionMenuItem(GUI main) {
		this.main = main;

		init();
	}

	/**
	 * initializes the GUI components
	 */
	public void init() {
		this.setText("New");

		this.addActionListener(this);
	}

	/**
	 * Action when menu item is pressed
	 */
	public void actionPerformed(ActionEvent e) {
		// TODO Phase 6 -- provide functionality for starting a new session of the HyPeerWeb
		PortNumber port = PortNumber.getApplicationsPortNumber();
		LocalObjectId localHyPeerWebId = HyPeerWebSegmentCreator.createHyPeerWeb(port.getValue());
		System.out.println("Local HyPeerWeb: " + localHyPeerWebId.toString());
		
		try {
			String myIPAddress = InetAddress.getLocalHost().getHostAddress();
			System.out.println(myIPAddress);
			HyPeerWebSegmentProxy hyPeerWebProxy = new HyPeerWebSegmentProxy(new GlobalObjectId(myIPAddress, new PortNumber(port), localHyPeerWebId));
			GUI.getSingleton().populate(hyPeerWebProxy);
		} catch (Exception ex) {
			System.err.println("Error after pressing \"new\"");
			System.err.println(ex.getMessage());
			ex.printStackTrace();
		}
	}
	
}
